﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using ITM495.Lab2.Core;
using ITM495.Lab2.Core.Entities;

namespace ITM495.Lab2.Impl.Readers
{
    public class CsvReader: IReader<Tweet>
    {
         protected String Path { get; set; }

        public CsvReader(string path)
        {
            Path = path;
        }

        #region IReader<Tweet> Members

        public IList<Tweet> Read()
        {
            var tweets = new List<Tweet>();

            using (var textReader = new StreamReader(Path))
            {
                var line = textReader.ReadLine();

                while (line != null)
                {
                    //Remove leading and trailing quotes
                    line = line.TrimEnd(new char[] {'\"'})
                                .TrimStart(new char[]{'\"'});

                    //We know that each column is delimted by "," so we'll just split on that.
                    var parts = line.Split(new[] { "\",\"" }, StringSplitOptions.RemoveEmptyEntries).ToList();

                   
                    var tweet = new Tweet()
                    {
                        Title = HttpUtility.HtmlDecode(parts[0]),
                        Description = HttpUtility.HtmlDecode(parts[1]),
                        PubDate = DateTime.Parse(parts[2]),
                        Guid = HttpUtility.HtmlDecode(parts[3]),
                        Link = HttpUtility.HtmlDecode(parts[4])
                    };

                    tweets.Add(tweet);

                    line = textReader.ReadLine();
                }
            }

            return tweets;
        }

        #endregion
    }
}
